<?php

namespace IDock\Insurance\ACIC\Request\NonCar;

use Exception;
use IDock\Insurance\ACIC\ACICEnums;
use IDock\Insurance\ACIC\Request\AllACICRequest;
use IDock\Insurance\ACIC\Response\NonCar\NonCarInquiryResponse;
use IDock\Printer\NonCar\NonCarSubCoveragePrinter;
use IDock\Visitor\NonCar\NonCarInquiryVisitor;
use IDock\Visitor\NonCar\NonCarProductVisitor;
use IDock\Visitor\Premium\PremiumRelationVisitor;

class NonCarInquiryRequest extends AllACICRequest
{
    protected $code = '0002';

    protected $response = NonCarInquiryResponse::class;

    protected $urlTip = '非车投保';

    public $noCarApi = true;

    /**
     * @var NonCarInquiryVisitor $visitor
     */
    protected $visitor;

    /**
     * @return array
     * @throws Exception
     */
    public function generate(): array
    {
        $data = [
            //投保人信息
            'Applicant' => $this->setRelatedInfo($this->visitor->getApplicantVisitor(), 'applicant'),
            //投保信息列表
            'PolicyInfoList' => ['PolicyInfo' => [
                //被保险人信息
                'Insured' => $this->setRelatedInfo($this->visitor->getInsuredVisitor(), 'insured'),
                //产品信息列表
                'ProductList' => ['ProductItem' => $this->setProductList($this->visitor->getNonCarList())]
            ]],
            //安诚落地渠道信息
            'Channel' => $this->setChannel(),
            //前端渠道平台上传信息
            'Platform' => $this->setPlatform(),
            //实名查验信息
            'RealNameCheck' => [
                'EndpointIp' => '', //用户终端IP
                'EndpointMac' => '', //用户终端Mac
            ],
        ];

        return $data;
    }

    /**
     * 投保人信息
     * @param PremiumRelationVisitor $premiumRelationVisitor
     * @param $type
     * @return array
     * @version 4.0
     */
    private function setRelatedInfo(PremiumRelationVisitor $premiumRelationVisitor, $type): array
    {
        $data = [
            'Name' => $premiumRelationVisitor->name,
            'CertificateType' => ACICEnums::$certificateTypeCode[$premiumRelationVisitor->certificateTypeCode] ?? '01',
            'CertificateNo' => $premiumRelationVisitor->certificateNo,
            'Contact' => $premiumRelationVisitor->name,
            'Phone' => $premiumRelationVisitor->mobile,
            'Address' => $premiumRelationVisitor->address,
            'OrganizationType' => '',
            'Age' => '',
            'Gender' => '',
            'EMAIL' => '',
            'Birthday' => '',
            'MaritalStatus' => '',
            'ClientType' => '',
            'CustomerDetail' => [
                'IDStartDate' => $premiumRelationVisitor->certificateStartDate,
                'IDEndDate' => $premiumRelationVisitor->certificateEndDate,
                'AddressDetail' => [
                    'Flag' => '0'
                ],
                'Nation' => 'CHN',
                'Income' => '10',
                'WorkOrg' => '',
                //职业明细信息
                'CareerDetail' => [
                    'FirstCode' => '40',
                    'SecondCode' => '4001',
                    'CareerCode' => '9900000',
                ],
                //机构明细信息
                'OrgDetail' => [
                    'Operate' => '',
                    'IndustryCode' => '',
                    'RegAmt' => '',
                    'RepName' => '',
                    'RepIDType' => '',
                    'RepIDNo' => '',
                    'RepIDStartDate' => '',
                    'RepIDEndDate' => '',
                    'ManName' => '',
                    'ManIDType' => '',
                    'ManIDNo' => '',
                    'ManIDStartDate' => '',
                    'ManIDEndDate' => '',
                    'OpeName' => '',
                    'OpeIDType' => '',
                    'OpeIDNo' => '',
                    'OpeIDStartDate' => '',
                    'OpeIDEndDate' => '',
                ],
            ],
            'School' => '',
            'Class' => '',
        ];

        if ($type == 'insured') {
            $data['Relationship'] = '601005'; //投保人与被保险人关系
            $data['BeneficiaryType'] = '2';
        }

        return $data;
    }

    /**
     * 产品列表待定
     * to-do
     * @param array $nonCarList
     * @return array
     * @version 4.0
     */
    private function setProductList(array $nonCarList): array
    {

        $data = [];

        //var_dump($this->visitor);exit;

        foreach ($nonCarList as $item) {
            /*** @var NonCarProductVisitor $item */
            $data[] = [
                'ProductId' => '0676', //驾乘人员意外伤害保险,
                'FrontProductName' => '驾乘无忧-(' . $item->premium . ')',
                'Policy' => [
                    'BillDate' => date('Ymd'),
                    'EffectiveDate' => date('YmdHis', strtotime($this->visitor->startData)),
                    'ExpireDate' => date('YmdHis', strtotime($this->visitor->endData)),
                    //保额合计
                    'TotalSumLimit' => array_sum(array_column($item->subCoverage, 'amount')) * $this->visitor->getVehicleVisitor()->vehicleSeat,
                    'TotalPremium' => array_sum(array_column($item->subCoverage, 'premium')),
                    'ProductType' => 'N',
                    'AppNo' => $this->visitor->argc['appNo'] ?? '',
                    //'SepcialAppoint' => '',
                    //'Count' => '',
                    //'Days' => '',
                    //'PeopleNum' => '',

                    //'PolicyNo' => '',
                    //'DocumentNo' => '',
                    //'CIPlanNo' => '',
                    //'ProductSubType' => '',
                    //'GreenInfo' => '',
                    //'EleBackLetter' => '',
                    //'PlyRiskLevel' => '',
                    //投保份数
                    'Cumulative' => $item->insuredNum,
                ],
                // 费用处理类型
                'FreeInfo' => [
                    'FreeType' => '2', //使用费用ID匹配
                    'FreeID' => $this->visitor->getNonCarList()[0]->subCoverage[0]->argc['FreeID'] ?? ''
                ],
                //受益人信息集合
                //'BeneficiaryList' => [],
                //险种明细列表
                'CoverageList' => ['Coverage' => $this->setCoverageList($item->subCoverage)],
                //保险标的
                'Subject' => [
                    'LicensePlateNo' => $this->visitor->getVehicleVisitor()->licenseNo,
                    'VIN' => $this->visitor->getVehicleVisitor()->vin,
                    'EngineNo' => $this->visitor->getVehicleVisitor()->engineNo,
                    'SeatNo' => $this->visitor->getVehicleVisitor()->vehicleSeat,
                    'MotorTypeCode' => $this->motorTypeCode(),
                    'MotorUsageTypeCode' => $this->usageTypeCode(),
                    'Owner' => $this->visitor->getOwnerVisitor()->name,
                    'OwnerCertificateType' => ACICEnums::$certificateTypeCode[$this->visitor->getOwnerVisitor()->certificateTypeCode] ?? '01',
                    'OwnerCertificateNo' => $this->visitor->getOwnerVisitor()->certificateNo,
                ],
                //组合投保时联合凭证号
                'UnionNo' => '',
            ];
        }

        return $data;
    }

    /**
     * 获取车辆种类代码
     * @return string
     */
    private function motorTypeCode(): string
    {
        $vehicleVisitor = $this->visitor->getVehicleVisitor();

        $carKindCode = $vehicleVisitor->carKindCode;
        $motorTypeCode = '';
        if ($carKindCode == '100') {
            if ($vehicleVisitor->vehicleSeat < 6) {
                $motorTypeCode = '11';
            }
            if ($vehicleVisitor->vehicleSeat >= 6 and $vehicleVisitor->vehicleSeat <= 9) {
                $motorTypeCode = '12';
            }
            if ($vehicleVisitor->vehicleSeat > 9) {
                $motorTypeCode = '13';
            }
        }

        if ($carKindCode == '200' or $carKindCode == '210') {
            if ($vehicleVisitor->vehicleTonnage < 2000) {
                $motorTypeCode = '21';
            }
            if ($vehicleVisitor->vehicleTonnage >= 2000 and $vehicleVisitor->vehicleTonnage < 10000) {
                $motorTypeCode = '22';
            }
            if ($vehicleVisitor->vehicleTonnage >= 10000) {
                $motorTypeCode = '23';
            }
        }

        return $motorTypeCode;
    }

    /**
     * 使用性质代码
     * @return string
     */
    private function usageTypeCode(): string
    {
        $vehicleVisitor = $this->visitor->getVehicleVisitor();

        $usageTypeCode = '';

        if ($vehicleVisitor->useNatureCode == '01') {
            $usageTypeCode = '200';
        }
        if ($vehicleVisitor->useNatureCode == '02') {
            $usageTypeCode = '100';
        }

        return $usageTypeCode;
    }

    /**
     * 险种明细
     * @param array $subCoverage
     * @return array
     */
    private function setCoverageList(array $subCoverage): array
    {
        $list = [];

        foreach ($subCoverage as $item) {
            /*** @var NonCarSubCoveragePrinter $item */
            $one = [
                'CoverageCode' => $item->subCode,
                'SumLimit' => $item->amount,
                'Premium' => $item->premium
            ];
            if ($item->argc['NoDuctAmt'] ?? '') {
                $one['NoDuctAmt'] = $item->argc['NoDuctAmt'];
            }
            $list[] = $one;
        }
        return $list;
    }

    /**
     * 安诚落地渠道信息
     * @return string[]
     * @version 4.0
     */
    private function setChannel(): array
    {

        $data = [
            'MatchFlag' => '0',
            'ID' => $this->visitor->argc['NCChannelId'] ?? '',
            'BusinessSrc' => '',
            'ChannelType' => '',
            'ChannelSubType' => '',
            'SalerCode' => '',
            'SalerName' => '',
            'OperatorCode' => '',
            'AgentCode' => '',
            'AgentContract' => '',
            'OrgCode' => '',
            'OrgAddress' => '',
            'AreaCode' => '',
        ];

        return $data;
    }

    /**
     * 前端渠道平台上传信息
     * @return string[]
     * @version 4.0
     */
    private function setPlatform(): array
    {
        return [
            'SubChannelId' => '',
            'DeptCode' => '',
            'SalerCode' => '',
            'Remark1' => '',
            'Remark2' => '',
            'Remark3' => '',
            'Remark4' => '',
            'Remark5' => '',
        ];
    }
}
